package com.xzk.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @Classname MyParamGatewayFilterFactory
 * @Description TODO
 * @Date 2020/9/23 20:11
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {


    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            //http://127.0.0.1:10010/api/user/7?name=ccc-ju   config.param = name
            ServerHttpRequest request = exchange.getRequest();
            if(request.getQueryParams().containsKey(config.param)){
                request.getQueryParams().get(config.param).forEach(param -> {
                    System.out.printf("----局部过滤器----获得参数 %s:%s---- ", config.param, param);
                });

            }

            return chain.filter(exchange);  //执行请求
        };
    }


    //读取过滤器配置的参数
    public static class Config{
        //对应配置在application.yml配置文件中的过滤器参数
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }

}
